package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.BeanMapUtils;
import com.itheima.common.utils.UtilFuns;

import com.itheima.domain.cargo.*;
import com.itheima.service.cargo.ContractService;
import com.itheima.service.cargo.ExportProductService;
import com.itheima.service.cargo.ExportService;
import com.itheima.vo.ExportProductVo;
import com.itheima.vo.ExportResult;
import com.itheima.vo.ExportVo;
import com.itheima.web.controller.BaseController;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;

import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {

    @Reference
    private ExportService exportService;
    @Reference
    private ContractService contractService;
    @Reference
    private ExportProductService exportProductService;

    @RequestMapping(value = "/exportPdf",name = "报运单pdf下载")
    public void exportPdf(String id) throws IOException, JRException {
        //根据id查询报运单
        Export export = exportService.findById(id);
        //查询报运单下货物
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(example);
        //找到pdf模板
        String path = session.getServletContext().getRealPath("/jasper/export.jasper");
        //使用工具类将对象转为map
        Map map = BeanMapUtils.beanToMap(export);

        //给模板添加数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(path, map, new JRBeanCollectionDataSource(list));
        //JasperPrint jp        = JasperFillManager.fillReport(path ,map, new JRBeanCollectionDataSource(list));
        //前往下载
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
    }

    @RequestMapping(value = "/exportE",name = "提交电子报运")
    public String exportE(String id){
        //- 根据id查询电子报运单，得到报运单对象
        Export export = exportService.findById(id);
        //- 转化成ws接口传递的实体类vo报运对象，并将报运单ID设置到vo对象中
        ExportVo exportVo = new ExportVo();
        BeanUtils.copyProperties(export,exportVo);
        exportVo.setExportId(export.getId());//设置当前报运单id
        //- 查询所有报运单下货物，并循环遍历
        ExportProductExample productExample = new ExportProductExample();
        productExample.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> products = exportProductService.findAll(productExample);
        List<ExportProductVo> list = new ArrayList<>();
        //- 循环报运单下的货物，转化成ws接口传递的实体类vo货物对象，并将报运单ID设置到vo对象中
        for (ExportProduct product : products) {
            ExportProductVo productVo = new ExportProductVo();
            BeanUtils.copyProperties(product,productVo);
            productVo.setExportProductId(product.getId());
            list.add(productVo);
        }

        //- 设置关系vo报运对象与vo货物对象之间的关系
        exportVo.setProducts(list);
        //- 通过WebClient向海关报运系统发送POST请求进行报运
        WebClient.create("http://localhost:9999/ws/export").type(MediaType.APPLICATION_JSON_TYPE).post(exportVo);
        //- 通过WebClient向海关报运系统发送GET请求查询报运结果，并对结果进行处理
        ExportResult exportResult = WebClient.create("http://localhost:9999/ws/export"+id).get(ExportResult.class);
            //- 在返回的结果中包含exportId,根据exportId查询Export,并设置export对象的remark和state,并更新
            //- 根据返回结果更新其对应货物的tax
        exportService.updateE(exportResult);
        //- 重定向到电子报运列表展示页面redirect:/cargo/export/list.do
        return "redirect:cargo/export/list.do";
    }

    @RequestMapping(value = "/contractList",name = " 前往合同管理页面")
    public String contractList(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "5") int size){
        ContractExample example = new ContractExample();
        example.createCriteria().andStateEqualTo(1).andCompanyIdEqualTo(getCurrentUserCompanyId());//根据企业id和合同状态为1的条件到合同管理分页页面
        example.setOrderByClause("create_time desc");//根据创建时间到序排序列表
        PageInfo pageInfo = contractService.findAll(example, page, size);//根据条件查询所有合同
        request.setAttribute("page",pageInfo);
        return "cargo/export/export-contractList";
    }

    @RequestMapping(value = "/toExport",name = "提交所选合同前往填写  出口报运表格")
    public String toExport(String id){
        request.setAttribute("id",id);//获取所有合同id值存入请求域
        return "cargo/export/export-toExport";
    }

    @RequestMapping(value = "/list",name = "前往出口报运")
    public String list(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "5") int size){
        ExportExample example = new ExportExample();
        example.createCriteria().andCompanyIdEqualTo(getCurrentUserCompanyId());
        example.setOrderByClause("create_time desc");

        PageInfo pageInfo = exportService.findAll(example, page, size);
        request.setAttribute("page",pageInfo);

        return "cargo/export/export-list";
    }

    @RequestMapping(value = "/edit",name = "保存或更新报运合同")
    public String edit(Export export){
        if(UtilFuns.isEmpty(export.getId())){
            //保存
            export.setCompanyId(getCurrentUserCompanyId());
            export.setCompanyName(getCurrenUserCompanyName());
            exportService.save(export);
        }else {
            //更新
            exportService.update(export);
        }
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "前往更新报运单页面")
    public String toUpdate(String id){
        //根据id查询报运单
        Export export = exportService.findById(id);
        request.setAttribute("export",export);

        //根据id查询报运单下所有货物
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);

        List<ExportProduct> all = exportProductService.findAll(exportProductExample);
        request.setAttribute("eps",all);
        return "/cargo/export/export-update";
    }

    @RequestMapping(value = "/toView",name = "前往查看货运单页面")
    public String toView(String id){
        //根据id查询报运单
        Export export = exportService.findById(id);
        request.setAttribute("export",export);

        //根据id查询报运单下所有货物
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);

        List<ExportProduct> all = exportProductService.findAll(exportProductExample);
        request.setAttribute("eps",all);
        return "/cargo/export/export-view";
    }

}
